require "yaml"

module RpmPackager
  def generate_spec_file
    cp_and_process File.join(File.dirname(__FILE__), '/../templates/spec.template'), File.join(RAILS_ROOT, "#{app_name}.spec") do |template| 
      instance_eval('"'+template+'"')
    end
  end
  
  def generate_container_config_file(haproxy_port, start_port)
    config_file = File.join(RAILS_ROOT, "config", "container.config")
    config = YAML.load_file File.join(File.dirname(__FILE__), '/../templates/container.config.template')
    config[:domain] = app_name
    config[:haproxy_port] = haproxy_port
    (1..4).each{|i| config[:"app_port#{i}"] = start_port + i - 1}
    write_to_file config_file, config.to_yaml
    config_file
  end
  
  def replace_shebang(file)
    cp_and_process(file, file){|src| src.sub(/#!.+\n/, "#!/usr/bin/env ruby")}
  end  
  
  def file_content(file)
    File.open(file){|f| f.read}
  end
  
  def method_missing(method_id)
    config_value = config[method_id.id2name]
    return config_value unless config_value.nil?
    super
  end
  
  def rm_svn(dir)
    cd dir do
      system "find -name .svn|xargs rm -rf"
    end
  end
  
  def gem_install_statement
    return "" unless gems
    statement = ""
    gems.each_pair do |key, value|
      statement = statement + "echo \"#{value}\" | " if value > 0
      statement = statement + "gem install #{key} --no-rdoc --no-ri -y && "
    end
    statement = statement + "echo"
    statement
  end
  
  private
  def cp_and_process(src_file, dest_file, &block)
    src = file_content src_file
    dest = yield src
    write_to_file dest_file, dest
  end

  def write_to_file(file, content)
    File.open(file, "w+"){|f| f.write content}
  end
  
  def config
    @config ||= YAML.load_file(File.join(File.dirname(__FILE__), '/../config.yml'))["configuration"]
  end
end